package com.tanhua.dubbo.api;

import com.tanhua.model.domain.PeachBlossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;

/**
 * @author lxb哦吼吼
 * @version 1.0
 * @description: TODO
 * @date 2021/11/17 15:13
 */

@DubboService
public class PeachApiImpl implements PeachApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveVoice(PeachBlossom peachBlossom) {
        mongoTemplate.save(peachBlossom);
    }

    @Override
    public PeachBlossom getVoiceRandom() {
        TypedAggregation<PeachBlossom> aggregation = Aggregation.newAggregation(PeachBlossom.class, Aggregation.sample(1));

        AggregationResults<PeachBlossom> peachBlossom = mongoTemplate.aggregate(aggregation, PeachBlossom.class);

        PeachBlossom uniqueMappedResult = peachBlossom.getUniqueMappedResult();

        mongoTemplate.remove(uniqueMappedResult);

        return peachBlossom.getMappedResults().get(0);
    }
}
